﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Helpers;
using HIWSystem.Models;

namespace HIWSystem.ViewModel
{
    public class IMDYieldQueryViewModel :ViewModelBase
    {
        //声明全局变量是为了方便导出报告使用
        DataTable dtYields= new DataTable(); //良率汇总数据
        DataTable dtIMDDetails = new DataTable(); //IMD详细数据
        private bool IsFirstFilter = true; //首次过滤机种标记
        private bool IsFirstFilterWO = true;//首次过滤工单标记
        ObservableCollection<PartNumberEntity> backupPNs = null;
        ObservableCollection<WOEntity> backupWOs = null;
        TrackingCombineSnEntity searchCondition = new TrackingCombineSnEntity(); //查询基础数据
        #region 属性
        private string pn;
        /// <summary>
        /// 机种信息
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private string searchPNText;
        /// <summary>
        /// ComboBox文本框输入的搜索文本
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        ///  选中的机种
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }

        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种信息
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private string selectedPN;
        /// <summary>
        /// 选中的机种
        /// </summary>
        public string SelectedPN
        {
            get { return selectedPN; }
            set { selectedPN = value; this.RaisePropertyChanged(() => SelectedPN); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否打开机种下拉列表框
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string wo;
        /// <summary>
        /// 机种信息
        /// </summary>
        public string WO
        {
            get { return wo; }
            set { wo = value; this.RaisePropertyChanged(() => WO); }
        }
        private string searchWOText;
        /// <summary>
        /// ComboBox文本框输入的搜索文本
        /// </summary>
        public string SearchWOText
        {
            get { return searchWOText; }
            set { searchWOText = value; this.RaisePropertyChanged(() => SearchWOText); }
        }
        private PartNumberEntity selectedWO;
        /// <summary>
        ///  选中的机种
        /// </summary>
        public PartNumberEntity SelectedWO
        {
            get { return selectedWO; }
            set { selectedWO = value; this.RaisePropertyChanged(() => SelectedWO); }
        }

        private ObservableCollection<WOEntity> wos;
        /// <summary>
        /// 机种信息
        /// </summary>
        public ObservableCollection<WOEntity> WOs
        {
            get { return wos; }
            set { wos = value; this.RaisePropertyChanged(() => WOs); }
        }
        private bool isOpenComboWODropDown;
        /// <summary>
        /// 是否打开机种下拉列表框
        /// </summary>
        public bool IsOpenComboWODropDown
        {
            get { return isOpenComboWODropDown; }
            set { isOpenComboWODropDown = value; this.RaisePropertyChanged(() => IsOpenComboWODropDown); }
        }
        private string actor;
        /// <summary>
        /// 工号
        /// </summary>
        public string Actor
        {
            get { return actor; }
            set { actor = value; this.RaisePropertyChanged(() => Actor); }
        }
        private ObservableCollection<TrackingEntity> sequences;
        /// <summary>
        /// 测序集合
        /// </summary>
        public ObservableCollection<TrackingEntity> Sequences
        {
            get { return sequences; }
            set { sequences = value; this.RaisePropertyChanged(() => Sequences); }
        }
        private TrackingEntity selectedSequence;
        /// <summary>
        /// 选择的测试项
        /// </summary>
        public TrackingEntity SelectedSequence
        {
            get { return selectedSequence; }
            set { selectedSequence = value; this.RaisePropertyChanged(() => SelectedSequence); }
        }
        private string testSequence;
        /// <summary>
        /// 选择的测序值
        /// </summary>
        public string TestSequence
        {
            get { return testSequence; }
            set { testSequence = value; this.RaisePropertyChanged(() => TestSequence); }
        }

        private ObservableCollection<IMDEntity> sources;
        /// <summary>
        /// 测序集合
        /// </summary>
        public ObservableCollection<IMDEntity> Sources
        {
            get { return sources; }
            set { sources = value; this.RaisePropertyChanged(() => Sources); }
        }
        private IMDEntity selectedSource;
        /// <summary>
        /// 选择的测试项
        /// </summary>
        public IMDEntity SelectedSource
        {
            get { return selectedSource; }
            set { selectedSource = value; this.RaisePropertyChanged(() => SelectedSource); }
        }
        private string source;
        /// <summary>
        /// 选择的测序值
        /// </summary>
        public string Source
        {
            get { return source; }
            set { source = value; this.RaisePropertyChanged(() => Source); }
        }
        private string startTime;
        /// <summary>
        /// 开始时间
        /// </summary>
        public string StartTime
        {
            get { return startTime; }
            set { startTime = value; this.RaisePropertyChanged(() => StartTime); }
        }
        private string stopTime;
        /// <summary>
        /// 结束时间
        /// </summary>
        public string StopTime
        {
            get { return stopTime; }
            set { stopTime = value; this.RaisePropertyChanged(() => StopTime); }
        }
        private bool isEnabledQueryButton = true;
        /// <summary>
        /// 是否启用查询按钮
        /// </summary>
        public bool IsEnabledQueryButton
        {
            get { return isEnabledQueryButton; }
            set { isEnabledQueryButton = value; this.RaisePropertyChanged(() => IsEnabledQueryButton); }
        }
        private Visibility isVisibleLoading = Visibility.Collapsed;
        /// <summary>
        /// 是否显示加载图标
        /// </summary>
        public Visibility IsVisibleLoading
        {
            get { return isVisibleLoading; }
            set { isVisibleLoading = value; this.RaisePropertyChanged(() => IsVisibleLoading); }
        }
        private bool isEnabledExportButton = true;
        /// <summary>
        /// 是否启用导出按钮
        /// </summary>
        public bool IsEnabledExportButton
        {
            get { return isEnabledExportButton; }
            set { isEnabledExportButton = value; this.RaisePropertyChanged(() => IsEnabledExportButton); }
        }
        private ObservableCollection<StationOutputEntity> summarys;
        /// <summary>
        /// 良率汇总
        /// </summary>
        public ObservableCollection<StationOutputEntity> Summarys
        {
            get { return summarys; }
            set { summarys = value; this.RaisePropertyChanged(() => Summarys); }
        }
        private ObservableCollection<TrackingEntity> details;
        /// <summary>
        /// 详细信息
        /// </summary>
        public ObservableCollection<TrackingEntity> Details
        {
            get { return details; }
            set { details = value; this.RaisePropertyChanged(() => Details); }
        }

        #endregion

        #region 命令
        private RelayCommand queryCmd;

        public RelayCommand QueryCmd
        {
            get {
                queryCmd = queryCmd ?? new RelayCommand(Query);
                return queryCmd; }
            set { queryCmd = value; }
        }

        private RelayCommand exportCmd;

        public RelayCommand ExportCmd
        {
            get {
                exportCmd = exportCmd ?? new RelayCommand(Export);
                return exportCmd; }
            set { exportCmd = value; }
        }
        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get {
                loadedPageCmd = loadedPageCmd ?? new RelayCommand(LoadedPage);
                return loadedPageCmd; }
            set { loadedPageCmd = value; }
        }
        private RelayCommand<string> comboPN_SelectionChangedCmd;

        public RelayCommand<string> ComboPN_SelectionChangedCmd
        {
            get {
                comboPN_SelectionChangedCmd = comboPN_SelectionChangedCmd ?? new RelayCommand<string>(ComboPNSelectedChanged);
                return comboPN_SelectionChangedCmd; }
            set { comboPN_SelectionChangedCmd = value; }
        }
        private RelayCommand<StationOutputEntity> showSummaryDetatilsCmd;

        public RelayCommand<StationOutputEntity> ShowSummaryDetatilsCmd
        {
            get
            {
                if (showSummaryDetatilsCmd == null)
                {
                    showSummaryDetatilsCmd = new RelayCommand<StationOutputEntity>(ShowSummaryDetailsHandler);
                }
                return showSummaryDetatilsCmd;
            }
            set { showSummaryDetatilsCmd = value; }
        }
        private RelayCommand filterPNCmd;

        public RelayCommand FilterPNCmd
        {
            get {
                filterPNCmd = filterPNCmd ?? new RelayCommand(FilterPN);
                return filterPNCmd; }
            set { filterPNCmd = value; }
        }
        private RelayCommand filterWOCmd;

        public RelayCommand FilterWOCmd
        {
            get {
                filterWOCmd = filterWOCmd ?? new RelayCommand(FilterWO);
                return filterWOCmd; }
            set { filterWOCmd = value; }
        }

        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            FillSequencesToComboBox();
            FillPNsToComboBox();
            FillSourcesToComboBox();
        }

        /// <summary>
        /// 导出报告
        /// </summary>
        private async void Export()
        {
            if (dtYields.Rows.Count == 0 && dtIMDDetails.Rows.Count == 0)
            {
                MessageBox.Show("没有数据需要导出", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (IsEnabledQueryButton == false)
            {
                MessageBox.Show("正在查询数据...待查询完再导出", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            //保存数据之前先关闭Excel
            BusinessProcess.KillProcess("EXCEL");
            this.IsEnabledExportButton = false;
            //创建Excel  
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing);    //创建工作簿（WorkBook：即Excel文件主体本身）  
            Microsoft.Office.Interop.Excel.Worksheet excelWS = (Microsoft.Office.Interop.Excel.Worksheet)excelWB.Worksheets[1];   //创建工作表（即Excel里的子表sheet） 1表示在子表sheet1里进行数据导出  
            //excelWS.Cells.NumberFormat = "@";     //  如果数据中存在数字类型 可以让它变文本格式显示  
            //将数据导入到工作表的单元格
            await Task.Run(() => {
                //显示加载动画
                this.IsVisibleLoading = Visibility.Visible;
                for (int i = 0; i < dtYields.Columns.Count; i++)
                {
                    excelWS.Cells[1, i + 1] = dtYields.Columns[i].ColumnName;
                }

                for (int i = 0; i < dtYields.Rows.Count; i++)
                {
                    for (int j = 0; j < dtYields.Columns.Count; j++)
                    {
                        excelWS.Cells[i + 2, j + 1] = dtYields.Rows[i][j].ToString();   //Excel单元格第一个从索引1开始 
                    }
                }
                //创建工作表（Worksheet：工作表，即Excel里的子表sheet）
                excelWS = (Microsoft.Office.Interop.Excel.Worksheet)excelWB.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                //设置表名
                excelWS.Name = "Details";
                //将数据导入到工作表的单元格
                for (int i = 0; i < dtIMDDetails.Columns.Count; i++)
                {
                    excelWS.Cells[1, i + 1] = dtIMDDetails.Columns[i].ColumnName;
                }

                for (int i = 0; i < dtIMDDetails.Rows.Count; i++)
                {
                    for (int j = 0; j < dtIMDDetails.Columns.Count; j++)
                    {
                        excelWS.Cells[i + 2, j + 1] = dtIMDDetails.Rows[i][j].ToString();   //Excel单元格第一个从索引1开始 
                    }
                }
                //关闭加载动画
                this.IsVisibleLoading = Visibility.Collapsed;
            });

            //使用对话框让用户选择保存位置和填写保存的文件名
            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

            sfd.Filter = "Excel工作簿(*.xlsx)|*.xlsx";

            sfd.FilterIndex = 1;

            sfd.RestoreDirectory = true;

            if (sfd.ShowDialog() == true)
            {
                string localFilePath = sfd.FileName.ToString(); //获得文件路径
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径

                //获取文件路径，不带文件名
                //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
                //给文件名前加上时间
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
                //在文件名里加字符
                //saveFileDialog1.FileName.Insert(1,"dameng");
                //System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件fs输出带文字或图片的文件，就看需求了
                excelWB.SaveAs(localFilePath);  //将其进行保存到指定的路径  
                excelWB.Close();
                excelApp.Quit();  //KillAllExcel(excelApp); 释放可能还没释放的进程
                MessageBox.Show("导出表格成功!");
                System.Diagnostics.Process.Start(localFilePath);//保存完成后  打开文件
            }
            this.IsEnabledExportButton = true;
        }
        /// <summary>
        /// 查询良率
        /// </summary>
        private void Query()
        {
            _=OnQueringAsync();
        }
        private async Task OnQueringAsync()
        {
            bool ret = false;
            string strMsg = string.Empty;
            string[] arrMsgs = new string[2];
            if (IsEnabledExportButton==false)
            {
               MessageBox.Show("正在导出报告...","软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Warning);
               return;
            }
            //检测开始时间是否大于结束时间
            if ((StartTime??"")!="" && (StopTime??"")!="")
            {
                if (DateTime.Compare(Convert.ToDateTime(StartTime),Convert.ToDateTime(StopTime))>=0)
                {
                    MessageBox.Show("开始时间大于结束时间，请重新选择!", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            try
            {
                IsEnabledQueryButton = false;//禁用查询按钮，防止重复点击
                IsVisibleLoading = Visibility.Visible;//显示加载动画
                switch (this.TestSequence)
                {
                    case "终测":
                        this.TestSequence = "2";
                        break;
                    case "首测":
                        this.TestSequence = "1";
                        break;
                    case "全部":
                        this.TestSequence = "*";
                        break;
                    default:
                        this.TestSequence = "2";
                        break;
                }
                searchCondition = new TrackingCombineSnEntity()
                {
                    Actor = this.Actor ?? "",
                    PN =this.PN=="--请选择--"?"": this.PN ?? "",
                    WO = this.WO=="--请选择--"?"":this.WO ?? "",
                    IMDInfo=new IMDEntity { Source=this.Source=="--请选择--"?"":this.Source??""},
                    StartTime=this.StartTime??"",
                    StopTime=this.StopTime??"",
                    TestSequence=this.TestSequence=="--请选择--"?"":this.TestSequence??""
                };
                var dic = new Dictionary<string, DataTable>();
                dic= await TakeYieldBasicDataAsync(searchCondition);
                strMsg = dic.First().Key;
                dtYields = dic.First().Value;
                arrMsgs = strMsg.Split('|');
                if (arrMsgs[0]=="NO" && dtYields.Rows.Count==0)
                {
                    MessageBox.Show("获取良率的基础数据时出现错误", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                ret = await ShowYieldDataTableToUIAsync(dtYields);
                if (!ret)
                {
                    MessageBox.Show("显示原始数据到前台时发生错误", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                IsEnabledQueryButton = true;
                IsVisibleLoading = Visibility.Collapsed; //隐藏加载动画
            }
           
        }
        /// <summary>
        /// 添加良率基础数据到UI界面
        /// </summary>
        /// <param name="dtSource">原始数据</param>
        /// <returns></returns>
        private async Task<bool> ShowYieldDataTableToUIAsync(DataTable dtSource)
        {
            var tmpSummarys = new ObservableCollection<StationOutputEntity>();
            try
            {
                await Task.Run(() =>
                {
                    for (int i = 0; i < dtSource.Rows.Count; i++)
                    {
                        if (dtSource.Columns.Contains("WO"))
                        {
                            tmpSummarys.Add(new StationOutputEntity
                            {
                                PN = dtSource.Rows[i]["PN"].ToString() ?? "",
                                WO = dtSource.Rows[i]["WO"].ToString() ?? "",
                                Station = dtSource.Rows[i]["Station"].ToString() ?? "",
                                Source = dtSource.Rows[i]["Source"].ToString() ?? "",
                                Pass = dtSource.Rows[i]["Pass"].ToString() ?? "",
                                Fail = dtSource.Rows[i]["Fail"].ToString() ?? "",
                                Total = dtSource.Rows[i]["Total"].ToString() ?? "",
                                Yield = dtSource.Rows[i]["Yield"].ToString() ?? ""
                            });
                        }
                        else
                        {
                            tmpSummarys.Add(new StationOutputEntity
                            {
                                PN = dtSource.Rows[i]["PN"].ToString() ?? "",
                                //WO = dtSource.Rows[i]["WO"].ToString() ?? "",
                                Station = dtSource.Rows[i]["Station"].ToString() ?? "",
                                Source = dtSource.Rows[i]["Source"].ToString() ?? "",
                                Pass = dtSource.Rows[i]["Pass"].ToString() ?? "",
                                Fail = dtSource.Rows[i]["Fail"].ToString() ?? "",
                                Total = dtSource.Rows[i]["Total"].ToString() ?? "",
                                Yield = dtSource.Rows[i]["Yield"].ToString() ?? ""
                            });
                        }
                       
                    }
                });
                Summarys = tmpSummarys;
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 异步获取良率的基础数据
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        private async Task<Dictionary<string,DataTable>> TakeYieldBasicDataAsync(TrackingCombineSnEntity entity)
        {
            
            try
            {
               return await Task.Run<Dictionary<string,DataTable>>(()=> {
                    Dictionary<string, DataTable> dic = new Dictionary<string, DataTable>();
                    var dt = new DataTable();
                    string retMsg=BusinessProcess.QueryIMDYields(entity, out dt);
                    dic.Add(retMsg, dt);
                    return dic;
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 显示汇总的详细信息
        /// </summary>
        /// <param name="obj">良率实体</param>
        private async void ShowSummaryDetailsHandler(StationOutputEntity obj)
        {
            
            if (obj!=null)
            {
                try
                {
                    string retMsg = string.Empty;
                    string[] arrMsgs = new string[2];
                    IsVisibleLoading = Visibility.Visible;//显示加载动画
                    var entity = new TrackingCombineSnEntity
                    {
                        Sn = searchCondition.Sn ?? "",
                        PN = obj.PN,
                        WO = obj.WO,
                        Station = obj.Station,
                        IMDInfo = new IMDEntity { Source = obj.Source ?? "" },
                        Actor = searchCondition.Actor ?? "",
                        TestSequence = searchCondition.TestSequence ?? "2",
                        StartTime = searchCondition.StartTime ?? "",
                        StopTime = searchCondition.StopTime ?? "",
                    };

                    var dicDetails = await TakeIMDBasicDataAsync(entity);
                    retMsg = dicDetails.First().Key;
                    arrMsgs = retMsg.Split('|');
                    dtIMDDetails = dicDetails.First().Value;
                    //提取数据成功
                    if (arrMsgs[0] == "OK")
                    {
                        var ret = await ShowIMDDetailsToUIAsync(dtIMDDetails);
                        if (!ret)
                        {
                            MessageBox.Show("详细数据显示到前台时出错", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("提取详细数据的时候出错【" + arrMsgs[1] + "】", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("提取详细数据的时候出错【" + ex.Message + "】", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                    LogHelper.WriteLog(ex.Message, ex);
                    throw new Exception(ex.Message);
                }
                finally
                {
                    IsVisibleLoading = Visibility.Collapsed; //关闭加载动画
                }
              
            }
        }
        /// <summary>
        /// 查询IMD详细数据
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        private async Task<Dictionary<string, DataTable>> TakeIMDBasicDataAsync(TrackingCombineSnEntity entity)
        {
            try
            {
                return await Task.Run<Dictionary<string, DataTable>>(() => {
                    Dictionary<string, DataTable> dic = new Dictionary<string, DataTable>();
                    var dt = new DataTable();
                    string retMsg = BusinessProcess.QueryIMDYieldDetails(entity, out dt);
                    dic.Add(retMsg, dt);
                    return dic;
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 显示详细数据到前台
        /// </summary>
        /// <param name="dtSource">原始数据</param>
        /// <returns></returns>
        private async Task<bool> ShowIMDDetailsToUIAsync(DataTable dtSource)
        {
            var tmpDetails = new ObservableCollection<TrackingEntity>();
            Details = new ObservableCollection<TrackingEntity>();
            try
            {
                await Task.Run(() =>
                {
                    for (int i = 0; i < dtSource.Rows.Count; i++)
                    {
                        tmpDetails.Add(new TrackingEntity
                        {
                            Sn=dtSource.Rows[i]["Sn"].ToString()??"",
                            WO = dtSource.Rows[i]["WO"].ToString() ?? "",
                            Station = dtSource.Rows[i]["Station"].ToString() ?? "",
                            Result = dtSource.Rows[i]["Result"].ToString() ?? "",
                            FailDescription = dtSource.Rows[i]["FailDescription"].ToString() ?? "",
                            FailValue = dtSource.Rows[i]["FailValue"].ToString() ?? "",
                            EquipmentName = dtSource.Rows[i]["EquipmentName"].ToString() ?? "",
                            TestSequence = dtSource.Rows[i]["TestSequence"].ToString() ?? "",
                            StartTime = dtSource.Rows[i]["StartTime"].ToString() ?? "",
                            StopTime = dtSource.Rows[i]["StopTime"].ToString() ?? "",
                            Duration = dtSource.Rows[i]["Duration"].ToString() ?? "",
                            Shift = dtSource.Rows[i]["Shift"].ToString() ?? "",
                            Actor = dtSource.Rows[i]["Actor"].ToString() ?? "",
                            IMDInfo=new IMDEntity 
                            { 
                                Source=dtSource.Rows[i]["Source"].ToString()??"",
                                TestValue=dtSource.Rows[i]["TestValue"].ToString()??"",
                                UpperLimit = dtSource.Rows[i]["UpperLimit"].ToString() ?? "",
                                LowerLimit = dtSource.Rows[i]["LowerLimit"].ToString() ?? "",
                            },
                            CreateAt = dtSource.Rows[i]["CreateAt"].ToString() ?? "",
                        });
                    }
                });
                Details = tmpDetails;
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 机种下拉列表框选择事件处理
        /// </summary>
        /// <param name="obj"></param>
        private void ComboPNSelectedChanged(string obj)
        {
            if (obj == null)
            {
                return;
            }
            DataTable dtWOs = new DataTable();
            DataTable dtPNInfo = new DataTable();
            dtWOs = BusinessProcess.GetWOsByPN(obj);
            WOs = new ObservableCollection<WOEntity>();
            WOs.Add(new WOEntity { WO = "--请选择--" });
            for (int i = 0; i < dtWOs.Rows.Count; i++)
            {
                WOs.Add(new WOEntity { WO = dtWOs.Rows[i]["WO"].ToString() });
            }
        }
        /// <summary>
        /// 填充机种信息
        /// </summary>
        private void FillPNsToComboBox()
        {
            DataTable dtPNs = new DataTable();
            dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
            PNs = new ObservableCollection<PartNumberEntity>();
            PNs.Add(new PartNumberEntity { PN = "--请选择--" });
            for (int i = 0; i < dtPNs.Rows.Count; i++)
            {
                PNs.Add(new PartNumberEntity
                {
                    PN = dtPNs.Rows[i]["PartNumber"].ToString()
                });
            }
        }
        /// <summary>
        /// 填充序列到下拉列表框
        /// </summary>
        private void FillSequencesToComboBox()
        {
            Sequences = new ObservableCollection<TrackingEntity>();
            Sequences.Add(new TrackingEntity { TestSequence = "--请选择--" });
            Sequences.Add(new TrackingEntity { TestSequence = "终测" });
            Sequences.Add(new TrackingEntity { TestSequence = "首测" });
            Sequences.Add(new TrackingEntity { TestSequence = "全部" });
        }
        /// <summary>
        /// 填充来源到下拉列表框
        /// </summary>
        private void FillSourcesToComboBox()
        {
            Sources = new ObservableCollection<IMDEntity>();
            Sources.Add(new IMDEntity { Source="--请选择--"});
            Sources.Add(new IMDEntity { Source = "新装" });
            Sources.Add(new IMDEntity { Source = "维修" });
            Sources.Add(new IMDEntity { Source = "OBA" });
        }
        //过滤机种
        protected void FilterPN()
        {
            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (IsFirstFilter)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                IsFirstFilter = false;
            }
            //backupPNs = PNs;
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }
            //OnPropertyChanged("Shops");
        }
        //过滤工单
        protected void FilterWO()
        {
            IsOpenComboWODropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (IsFirstFilterWO)
            {
                backupWOs = new ObservableCollection<WOEntity>();
                backupWOs = WOs;
                IsFirstFilterWO = false;
            }
            //backupPNs = PNs;
            if (!string.IsNullOrEmpty(SearchWOText))
            {
                IEnumerable<WOEntity> WOEntities = WOs.Where(w => w.WO.ToUpper().Contains(SearchWOText.ToUpper()));
                WOs = new ObservableCollection<WOEntity>();
                foreach (var w in WOEntities)
                {
                    WOs.Add(w);
                }
            }
            else
            {
                WOs = backupWOs;
            }
            //OnPropertyChanged("Shops");
        }
        #endregion

    }
}
